package com.tmobile.book.irishcoffee;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import nl.siegmann.epublib.domain.Book;
import nl.siegmann.epublib.domain.Resource;
import nl.siegmann.epublib.domain.Spine;
import nl.siegmann.epublib.domain.SpineReference;
import nl.siegmann.epublib.epub.EpubReader;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.AssetManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;

public class LauncherActivity extends Activity {
	private static final String TAG = "LauncherActivity";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_launcher);
		if (!AppSingleton.getInstance().isDataLoaded()) {
			new LoadDataAsync().execute();
		}else {
			startActivity();
		}
	}

	private class LoadDataAsync extends AsyncTask<Void, Void, Void> {
		ProgressDialog dialog;

		@Override
		protected void onPreExecute() {

			dialog = new ProgressDialog(LauncherActivity.this);
			dialog.setMessage(getString(R.string.loading));
			dialog.show();
			super.onPreExecute();
		}

		@Override
		protected Void doInBackground(Void... params) {
			readEpubFile(Constants.filePath);
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			if (dialog.isShowing())
				dialog.dismiss();
			super.onPostExecute(result);
			AppSingleton.getInstance().setDataLoaded(true);
			startActivity();
		}

	}

	private void startActivity() {
		startActivity(new Intent(getApplicationContext(), MainActivity.class));
	}

	private void readEpubFile(String filePath) {
		AssetManager assetManager = getAssets();
		try {
			// find InputStream for book
			InputStream epubInputStream = assetManager.open(filePath);

			// Load Book from inputStream
			Book book = (new EpubReader()).readEpub(epubInputStream);

			// Log the book's authors
			// Log.i(TAG, "author : " + book.getMetadata().getAuthors());

			// Log the book's title
			// Log.i(TAG, "title : " + book.getTitle());

			/* Log the book's coverimage property */
			// Bitmap coverImage =
			// BitmapFactory.decodeStream(book.getCoverImage()
			// .getInputStream());
			// Log.i("epublib", "Coverimage is " + coverImage.getWidth() +
			// " by "
			// + coverImage.getHeight() + " pixels");

			// Log the tale of contents
			// logTableOfContents(book.getTableOfContents().getTocReferences(),
			// 0);
			readTableOfContents(book);

		} catch (IOException e) {
			Log.e(TAG, "epublib exception " + e.toString());
		}

		String javascrips = "";
		try {
			// InputStream input = getResources().openRawResource(R.raw.lights);
			InputStream input = this.getAssets().open(filePath);

			int size;
			size = input.available();
			byte[] buffer = new byte[size];
			input.read(buffer);
			input.close();
			// byte buffer into a string
			javascrips = new String(buffer);
		} catch (IOException e) {
			e.printStackTrace();
		}
		// String html = readFile(is);

		// webview.loadDataWithBaseURL("file:///android_asset/", javascrips,
		// "application/epub+zip", "UTF-8", null);
	}

	private void readTableOfContents(Book book) {
		Spine spine = new Spine(book.getTableOfContents());
		int index = 0;
		for (SpineReference bookSection : spine.getSpineReferences()) {
			index++;
			// Log.d(TAG, "index " + index);
			StringBuffer sb = new StringBuffer();
			Resource res = bookSection.getResource();
			try {
				InputStream is = res.getInputStream();
				BufferedReader r = new BufferedReader(new InputStreamReader(is));
				String line, lineX = "";
				while ((line = r.readLine()) != null) {
					lineX = lineX.concat(Html.fromHtml(line).toString())
							.concat("\n");
					sb.append(line);
					// Log.d(TAG, line);
				}
				AppSingleton.getInstance().addToChapterContent(sb.toString());
			} catch (IOException e) {
			}
		}
	}

}
